﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using WinAutomator.Library;

namespace WinAutomator.Library
{
    public class PluginManager
    {
        static PluginManager _instance;
        public static String PluginsDirectory;

        String _dir;
        List<IPlugin> _plugins = new List<IPlugin>();

        public PluginManager(String dir)
        {
            _dir = dir;
        }

        public static PluginManager Instance
        {
            get
            {
                if (_instance == null)
                {
                    _instance = new PluginManager(PluginsDirectory);
                    _instance.LoadPlugin();
                }

                return _instance;
            }
            
        }

        public bool LoadPlugin()
        {
            string path = _dir;
            string[] pluginFiles = Directory.GetFiles(path, "*.dll");

            for (int i = 0; i < pluginFiles.Length; i++)
            {
                try
                {
                    // load it
                    Assembly ass = null;
                    ass = Assembly.LoadFrom(pluginFiles[i]);
                    Type[] types = ass.GetTypes();
                    foreach (Type t in types)
                        if (t.GetInterface("IPlugin") != null)
                            _plugins.Add((IPlugin)Activator.CreateInstance(t));
                }
                catch (Exception ex)
                {
                    return false;
                }
            }
            return true;
        }

        public List<IPlugin> Plugins
        {
            get
            {
                return _plugins;
            }
        }

        public IPlugin CreateInstance(IPlugin plugin)
        {
            return (IPlugin)Activator.CreateInstance(plugin.GetType());
        }
    }
}
